package com.work.demo.redis;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Arrays;

/**
 * @ClassName : JedisSingleTest
 * @Description :
 * @Author : LinYa
 * @Date: 2021/12/13  17:32
 */
public class JedisSingleTest {

	public static void main(String[] args) {
		JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
		jedisPoolConfig.setMaxTotal(20);
		jedisPoolConfig.setMaxIdle(10);
		jedisPoolConfig.setMinIdle(5);

		JedisPool jedisPool = new JedisPool(jedisPoolConfig, "114.55.105.70", 6379, 3000, null);

		Jedis jedis = null;

		try {
			//从redis连接池里拿出一个连接执行命令
			jedis = jedisPool.getResource();
			//****** jedis普通操作示例 ******
			//System.out.println(jedis.set("linyajedis","linya"));
			//System.out.println(jedis.get("linyajedis"));

			//****** 管道示例 ******
			//特点：不管插入数据是否成功或者失败，都会返回插入结果。并没有回滚机制
//			Pipeline pl = jedis.pipelined();
//			for (int i = 0; i < 10; i++) {
//				//插入redis原子自增
//				pl.incr("pipelineKey");
//
//				pl.set("linya"+i,"linya");
//
//			}
//
//			List<Object> objects = pl.syncAndReturnAll();
//			System.out.println(objects);

			// ******* lua脚本示例 *************
			jedis.set("product_stock_10016", "15");
			String script = " local count = redis.call('get',KEYS[1])" +
							" local a = tonumber(count)" +
							" local b = tonumber(ARGV[1])" +
							" if a>= b then " +
							"	  redis.call('set',KEYS[1], a-b)" +
							//"   bb == 0" + //模拟语法错误回滚操作
							"   return 1" +
							" end" +
							" return 0 ";
			Object obj = jedis.eval(script, Arrays.asList("product_stock_10016"), Arrays.asList("10"));
			System.out.println(obj);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}

	}
}
